package app.jobs;

import app.Const;
import app.dtos.IntegralType;
import app.models.member.Account;
import app.models.member.IntegralRecord;
import app.models.member.Invite;
import app.models.member.Member;
import app.models.member.Points;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import goja.Logger;
import goja.StringPool;
import goja.job.Job;
import org.joda.time.DateTime;

/**
 * <p> 邀请人奖励计算 </p>
 *
 * @author sogYF
 * @version 1.0
 * @since JDK 1.6
 */
public class InviteMemberJob extends Job<Boolean> {
    private final String phone;

    private final String invitePhone;
    private final int    new_member;

    private final DateTime regTime;

    public InviteMemberJob(String phone, String invitePhone, int new_member, DateTime regTime) {

        this.phone = phone;
        this.invitePhone = invitePhone;
        this.new_member = new_member;
        this.regTime = regTime;
    }

    @Override
    public Boolean doJobWithResult() throws Exception {
        if(Strings.isNullOrEmpty(invitePhone)){
            return false;
        }
        // 推荐人
        Member member = Member.dao.findbyPhone(invitePhone);
        if(member == null ){
            Logger.error("invite phone is not exist!");
            return false;
        }
        Optional<Points> option_point = Points.dao.findByCode(Const.POINTS_CODE.INVITE);

        if (option_point.isPresent()) {
            Points points = option_point.get();
            if (points.getNumber(Const.FIELD_STATUS).intValue() == 1) {
                int integral = points.getNumber(Const.FIELD_INTEGRAL).intValue();

                final int memberId = member.getNumber(StringPool.PK_COLUMN).intValue();
                Account account = Account.dao.findbyMember(memberId);
                final Number exist_integral = account.getNumber(Const.FIELD_INTEGRAL);

                final int balance = (exist_integral == null) ? integral : exist_integral.intValue() + integral;
                account.set(Const.FIELD_INTEGRAL, balance);
                if (account.update()) {
                    IntegralRecord.dao.earning(DateTime.now(), memberId, IntegralType.INVITE, "邀请会员成功奖励", integral, balance);
                }

                Invite invite = new Invite();
                DateTime now = DateTime.now();
                invite.set(Const.FIELD_MEMBER, memberId);
                invite.set("phone", phone);
                invite.set(Const.FIELD_INTEGRAL, integral);
                invite.set("invite_time", now);
                invite.set("new_member", new_member);
                invite.set("reg_time", regTime);
                invite.set("reg_time_year", regTime.getYear());
                invite.set("reg_time_month", regTime.getMonthOfYear());
                invite.set("reg_time_day", regTime.getDayOfMonth());

                return invite.save();


            }
        }
        return false;

    }
}
